
import * as vscode from 'vscode';
import { ExtensionToWebviewMessage,MessageSubscriber, WebviewToExtensionMessage } from '../types/types';
import { IAgentBus } from './IAgentBus';
import { ErrorHandler, ErrorLevel } from '../utils/ErrorHandler';


export class TestAgentBus implements IAgentBus {

    private _subscribers: MessageSubscriber[] = []; // 存储所有订阅者的数组

    private _pendingMessages: Map<string,(approved: boolean) => void> = new Map(); // 存储待处理消息的数组

    private _webview?: vscode.Webview; // 存储Webview实例


    // 注册Webview实例，接受一个vscode.Webview类型的参数和一个vscode.Disposable数组,用于监听来自Webview的消息
    public registerWebview(webview: vscode.Webview, disposables: vscode.Disposable[]): void {

        
        this._webview = webview; // 存储Webview实例

        // 监听来自Webview的消息
        webview.onDidReceiveMessage(async (message: WebviewToExtensionMessage) => {
            
            if (message.type === 'toolConfirmationResponse') {
                this.handleResponse(message.messageId, message.approved);
                return; 
            }

            // 遍历所有订阅者并调用它们的回调函数处理消息
            const dispatchPromises = this._subscribers.map(async (subscriber) => {   
                        try {
                            await subscriber(message);
                        } catch (error) {
                            ErrorHandler.handle(
                                error instanceof Error ? error : new Error(String(error)),
                                { level: ErrorLevel.Error }
                            );
                        }
            });
            await Promise.all(dispatchPromises); // 等待所有订阅者处理完消息
        }, null, disposables);
        console.log('[AgentMessenger] Webview registered and listening.');
    }


    /** 发送消息 */
    public async sendMessage(message: ExtensionToWebviewMessage): Promise<void> {
            await this.post(message);
    }

    /**
     *Request-Response 模式
     * 发送消息 -> 存下 Promise -> 等待前端回传 -> 触发 Promise
     */
    public requestConfirmation(toolCall: any): Promise<boolean> {
        return new Promise<boolean>((resolve) => {
            // 1. 生成唯一 ID
            const messageId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            
            // 2. 将 resolve 函数存入 Map，等待被唤醒
            // 当 handleResponse 被调用时，这个 resolve 会被执行
            this._pendingMessages.set(messageId, resolve);

            console.log(`[AgentMessenger] Requesting confirmation, id: ${messageId}`);

            // 3. 发送请求给前端
            this.post({ 
                type: 'toolConfirmation', 
                toolCall, 
                messageId 
            });
            
            // 4. (可选) 设置超时自动拒绝，防止 Controller 永远卡住
            // 30秒后如果没有响应，自动 resolve(false)
            setTimeout(() => {
                if (this._pendingMessages.has(messageId)) {
                    console.warn(`[AgentMessenger] Confirmation timed out: ${messageId}`);
                    this._pendingMessages.delete(messageId);
                    resolve(false); // 超时视为拒绝
                }
            }, 30000);
        });
    }


    /**   
     * 注册消息监听器
     * Controller 通过此方法订阅前端发来的消息
     */
    public subscribe(subscriber: MessageSubscriber): void {
        this._subscribers.push(subscriber);
    }

    /**
     *处理响应消息
     * 唤醒沉睡的 Promise
     */
    private handleResponse(messageId: string, approved: boolean) {
        const resolve = this._pendingMessages.get(messageId);
        if (resolve) {
            console.log(`[AgentMessenger] Received confirmation response: ${messageId} -> ${approved}`);
            resolve(approved); // 唤醒 Promise
            this._pendingMessages.delete(messageId); // 清理内存
        } else {
            console.warn(`[AgentMessenger] Received response for unknown id: ${messageId}`);
        }
    }

    
    /**
     * 统一的底层发送方法
     * 封装了 webview 是否存在的检查
     */
    private async post(message: ExtensionToWebviewMessage): Promise<void> {
        if (this._webview) {
            // postMessage 返回 Thenable<boolean>
            await this._webview.postMessage(message);
        } else {
            console.warn('[AgentMessenger] Webview is not ready. Message lost:', message);
        }
    }

    /**
     * 清理资源,防止内存泄漏
     */
    public dispose(): void {
        // 清理所有未完成的 Promise
        this._pendingMessages.forEach((resolve, messageId) => {
            console.warn(`[AgentMessenger] Disposing pending message: ${messageId}`);
            resolve(false); // 所有未完成的请求视为拒绝
        });
        this._pendingMessages.clear();
        
        // 清理订阅者
        this._subscribers = [];
        
        // 清空 webview 引用
        this._webview = undefined;
        
        console.log('[AgentMessenger] Disposed');
    }

}